package com.zzh.takeoutapp.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.CarAdapter;
import com.zzh.takeoutapp.adapter.DetailAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.behaviors.DetailHeaderBehavior;
import com.zzh.takeoutapp.entity.FoodBean;
import com.zzh.takeoutapp.event.FoobEvent;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.utils.BaseUtils;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.utils.SPUtils;
import com.zzh.takeoutapp.view.goods.AddWidget;
import com.zzh.takeoutapp.view.goods.ShopCarView;
import com.zzh.takeoutapp.view.goods.ViewUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class DetailActivity extends BaseActivity implements AddWidget.OnAddClick {
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.detail_main)
    CoordinatorLayout detail_main;
    @Bind(R.id.headerview)
    View headerView;
    @Bind(R.id.iv_detail)
    ImageView iv_detail;
    @Bind(R.id.ic_close)
    ImageView ic_close;
    @Bind(R.id.toolbar_title)
    TextView toolbar_title;
    @Bind(R.id.detail_name)
    TextView detail_name;
    @Bind(R.id.detail_sale)
    TextView detail_sale;
    @Bind(R.id.detail_price)
    TextView detail_price;
    @Bind(R.id.detail_recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.detail_add)
    AddWidget detail_add;
    private FoodBean foodBean;
    public BottomSheetBehavior behavior;
    private ShopCarView shopCarView;
    private CarAdapter carAdapter;
    private DetailHeaderBehavior dhb;
    private int position = -1;
    private DetailAdapter dAdapter;
    private Context mContext;
    public String Shop_id;
    public StringBuffer buffer;
    private String Cate_id;
    private boolean dealCar = false;

    @Override
    public void setContent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.transparent));
        }
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        mContext = this;
        SPUtils.saveString(mContext, "key_id", "");
        foodBean = (FoodBean) getIntent().getSerializableExtra("food");
        position = getIntent().getIntExtra("position", -1);
        dealCar = false;
        initViews();
    }

    @Override
    public void initComponent() {

    }

    @Override
    public void setListener() {
        shopCarView.setmOnItemClickLitener(new ShopCarView.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {
                List<FoodBean> data = carAdapter.getData();
                if (data.size() != 0) {
                    buffer = new StringBuffer();
                    for (int i = 0; i < data.size(); i++) {
                        String Product_id = data.get(i).getProduct_id();
                        long selectCount = data.get(i).getSelectCount();
                        String Is_discount = data.get(i).getIs_discount();
                        Shop_id = data.get(i).getShop_id();
                        Cate_id = data.get(i).getCate_id();
                        buffer.append(Product_id + ":" + Is_discount + ":" + selectCount + "&,");
                    }
                    String substring = buffer.toString().substring(0, buffer.toString().length() - 1);
                    Log.e("jsonObject", substring);
                    Intent intent = new Intent();
                    intent.setClass(DetailActivity.this, SubmitOrderActivity.class);
                    intent.putExtra("Shop_id", Shop_id);
                    intent.putExtra("buffer", substring);
                    start_Activity(intent);
                }
            }
        });
    }

    @Override
    public void onAfterInit() {

    }

    @OnClick({R.id.ic_close})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ic_close:
                finish_Activity();
                break;
        }
    }

    private void initViews() {
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) headerView.getLayoutParams();
        dhb = (DetailHeaderBehavior) lp.getBehavior();
        ImageManager.loadUrlImage(this, foodBean.getPhoto(), iv_detail);
        toolbar_title.setText(foodBean.getName());
        detail_name.setText(foodBean.getName());
        detail_sale.setText(foodBean.getSale() + " 好评率95%");
        detail_price.setText(foodBean.getStrPrice(this));
        initRecyclerView();
        initShopCar();
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new SpaceItemDecoration());
        ((DefaultItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        dAdapter = new DetailAdapter(BaseUtils.getDetails(OrderCarDatelisActivity.foodBeanDatas), this);
        dAdapter.bindToRecyclerView(recyclerView);
    }


    private void initShopCar() {
        shopCarView = (ShopCarView) findViewById(R.id.car_mainfl);
        final View blackView = findViewById(R.id.blackview);
        behavior = BottomSheetBehavior.from(findViewById(R.id.car_container));
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                shopCarView.sheetScrolling = false;
                dhb.setDragable(false);
                if (newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN) {
                    blackView.setVisibility(View.GONE);
                    dhb.setDragable(true);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                shopCarView.sheetScrolling = true;
                blackView.setVisibility(View.VISIBLE);
                ViewCompat.setAlpha(blackView, slideOffset);
            }
        });
        blackView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                return true;
            }
        });
        shopCarView.setBehavior(behavior);
        RecyclerView carRecView = (RecyclerView) findViewById(R.id.car_recyclerview);
        carRecView.setLayoutManager(new LinearLayoutManager(this));
        ((DefaultItemAnimator) carRecView.getItemAnimator()).setSupportsChangeAnimations(false);
        ArrayList<FoodBean> flist = new ArrayList<>();
        flist.addAll(OrderCarDatelisActivity.carAdapter.getData());
        carAdapter = new CarAdapter(flist, this);
        carAdapter.bindToRecyclerView(carRecView);
        List<FoodBean> list = new ArrayList<>();
        list.add(foodBean);
        detail_add.setData(dAdapter, this, list, foodBean);
        detail_add.setState(foodBean.getSelectCount());
        shopCarView.post(new Runnable() {
            @Override
            public void run() {
                dealCar(foodBean);
            }
        });
    }


    private void dealCar(FoodBean foodBean) {
        BigDecimal amount = new BigDecimal(0.0);
        int total = 0;
        boolean hasFood = false;
        if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED
                || foodBean.getProduct_id().equals(this.foodBean.getProduct_id()) && foodBean.getSelectCount() !=
                this.foodBean.getSelectCount()) {
            this.foodBean = foodBean;
            detail_add.expendAdd(foodBean.getSelectCount());
        }
        List<FoodBean> flist = carAdapter.getData();
        int p = -1;
        for (int i = 0; i < flist.size(); i++) {
            FoodBean fb = flist.get(i);
            hasFood = true;
            total += fb.getSelectCount();
            amount = amount.add(fb.getPrice().multiply(BigDecimal.valueOf(fb.getSelectCount())));
            if (fb.getProduct_id().equals(foodBean.getProduct_id())) {
                if (foodBean.getSelectCount() == 0) {
                    p = i;
                } else {
                    carAdapter.setData(i, foodBean);
                }
            }
        }
        if (p >= 0) {
            carAdapter.remove(p);
        } else if (!hasFood && foodBean.getSelectCount() > 0) {
            carAdapter.addData(foodBean);
            amount = amount.add(foodBean.getPrice().multiply(BigDecimal.valueOf(foodBean.getSelectCount())));
            total += foodBean.getSelectCount();
        }
        shopCarView.showBadge(total);
        shopCarView.updateAmount(amount);
        if (dealCar == true) {
            FoobEvent foobEvent = new FoobEvent();
            if (foodBean.getProduct_id().equals(this.foodBean.getProduct_id())) {
                foobEvent.setPosition(position);
            }
            foobEvent.setBean(foodBean);
            foobEvent.setMsgType("dealCar");
            EventbusHelper.post(foobEvent);
        }

    }

    @Override
    public void onAddClick(View view, FoodBean fb, FoodBean foodBean1) {
        dealCar = true;
        if (fb.getIs_spec().equals("0")) {
            dealCar(fb);
        } else {
            dealCar(foodBean1);
        }
        ViewUtils.addTvAnim(view, shopCarView.carLoc, this, detail_main);
    }

    @Override
    public void onSubClick(FoodBean fb, FoodBean foodBean1) {
        dealCar = true;
        if (fb.getIs_spec().equals("0")) {
            dealCar(fb);
        } else {
            dealCar(foodBean1);
        }
    }

    private class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        SpaceItemDecoration() {
            this.space = ViewUtils.dip2px(mContext, 2);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.top = space;
            outRect.right = space;
            if (parent.getChildLayoutPosition(view) % 2 == 0) {
                outRect.left = 0;
            }
        }

    }


    public void clearCar(View view) {
        ViewUtils.showClearCar(this, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                List<FoodBean> flist = carAdapter.getData();
                for (int i = 0; i < flist.size(); i++) {
                    FoodBean fb = flist.get(i);
                    fb.setSelectCount(0);
                }
                List<FoodBean> list = new ArrayList<>();
                foodBean.setSelectCount(0);
                list.add(foodBean);
                detail_add.setData(dAdapter, DetailActivity.this, list, foodBean);
                detail_add.setState(foodBean.getSelectCount());
                detail_add.expendAdd(foodBean.getSelectCount());
                carAdapter.setNewData(new ArrayList<FoodBean>());
                shopCarView.showBadge(0);
                shopCarView.updateAmount(new BigDecimal(0.0));
                FoobEvent foobEvent = new FoobEvent();
                foobEvent.setMsgType("clearCar");
                EventbusHelper.post(foobEvent);
            }
        });
    }
}
